package movieGandalf.DB;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import movieGandalf.dataObjects.Director;

public class DirectorsReader implements DataReader{
	
	/*public int read(HashMap<Long,Object> dest, Encoder enc, Connection conn, InputStream in){
		String line = null;
		String name = null;
		
		try {
			boolean isBegin = true;
			while ((line = MovieTools.getLine(in)) != null){
				int len=line.length();
				
				if (isBegin){
					if (len<6 || !line.subSequence(0, 4).equals("Name") || !line.subSequence(len-6, len).equals("Titles"))
						continue;
					else{
						isBegin = false;
						line = MovieTools.getLine(in);
						continue;
					}
				}
				
				int i = 0;
				for (i=0;i<len;i++){
					if (line.charAt(i)=='\t') {
						break;
					}
				}
				
				if (i==0)
					continue;
				else if (i==len)
					i = len - 1;

				name = line.substring(0, i);
				
				dest.put(enc.encode(name), new Director(null, name, name));
			}
		}
		catch (Exception e){
			e.printStackTrace();
		}
		finally {
			try{
				in.close();
			}
			catch(Exception e){
				return 0;
			}
		}
		
		return 1;
	}*/
	
	
	public int read(Connection conn, InputStream in){
		String line = null;
		List<String> directorNames = new LinkedList<String>();
		
		try {
			boolean isBegin = true;
			while ((line = MovieTools.getLine(in)) != null){
				int len=line.length();
				
				if (isBegin){
					if (len<6 || !line.subSequence(0, 4).equals("Name") || !line.subSequence(len-6, len).equals("Titles"))
						continue;
					else{
						isBegin = false;
						line = MovieTools.getLine(in);
						continue;
					}
				}
				
				int i = 0;
				for (i=0;i<len;i++){
					if (line.charAt(i)=='\t') {
						break;
					}
				}
				
				if (i==0)
					continue;
				else if (i==len)
					i = len - 1;
				try{
					directorNames.add(line.substring(0, i));
				}
				catch (Exception e){
					e.getMessage();
				}
			}

			PreparedStatement stmt = conn.prepareStatement(new String("REPLACE INTO Directors (directorName,imdbName) VALUES (?,?)"));
			
			Iterator<String> iter = directorNames.iterator();
			String directorName = null;
			
			while (iter.hasNext()){
				directorName = iter.next();
				stmt.setString(1, directorName);
				stmt.setString(2, directorName);
				stmt.addBatch();
			}
			stmt.executeBatch();
			conn.commit();
			
			stmt.close();
		}
		
		catch (SQLException e) {
			e.printStackTrace();
			return 0;
		}
		catch (Exception e){
			e.printStackTrace();
		}
		finally {
			try{
				in.close();
			}
			catch(Exception e){
				return 0;
			}
		}
		
		return 1;
	}
	
}
